package api

import (
	"webserver/app/define"
	"webserver/library/error"
	"webserver/library/response"
	"webserver/library/utils"

	"github.com/gogf/gf/net/ghttp"
)

var Ajax = ajaxApi{}

type ajaxApi struct{}

func (*ajaxApi) DoPost(r *ghttp.Request) {
	var param *define.AjaxReq
	if err := r.Parse(&param); err != nil {
		response.JsonExit(r, 1, error.GvalidError(err).FirstString())
	}
	rsp, err := utils.HttpPost(param.Url, param.Param, param.Header)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	ret, err := utils.HttpResultToJson(rsp)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.JsonExit(r, 0, "success", ret)
}

func (*ajaxApi) DoGet(r *ghttp.Request) {
	var param *define.AjaxReq
	if err := r.Parse(&param); err != nil {
		response.JsonExit(r, 1, error.GvalidError(err).FirstString())
	}
	rsp, err := utils.HttpGet(param.Url, param.Header)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	ret, err := utils.HttpResultToJson(rsp)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.JsonExit(r, 0, "success", ret)
}

func (*ajaxApi) GetCookie(r *ghttp.Request) {
	var param *define.AjaxReq
	if err := r.Parse(&param); err != nil {
		response.JsonExit(r, 1, error.GvalidError(err).FirstString())
	}
	rsp, err := utils.GetUrlCookie(param.Url, param.Header)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.JsonExit(r, 0, "success", rsp)
}

func (*ajaxApi) GetHtml(r *ghttp.Request) {
	var param *define.AjaxReq
	if err := r.Parse(&param); err != nil {
		response.JsonExit(r, 1, error.GvalidError(err).FirstString())
	}
	rsp, err := utils.GetUrlHtml(param.Url, param.Header)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.JsonExit(r, 0, "success", rsp)
}
